import Q  from './bce-bos-uploader-lite/vendor/q';
import StsTokenManager  from './bce-bos-uploader-lite/sts_token_manager';
import Uploader  from './bce-bos-uploader-lite/uploader';
import wx from '../utils/wx';
function generateKey(path,file){
    var name = file.name,
      type = file.type;
    var date = new Date(),
      year = date.getFullYear(),
      month = date.getMonth() + 1,
      day = date.getDate(),
      milliSeconds = date.getMilliseconds(),
      hour = date.getHours(),
      minute = date.getMinutes(),
      second = date.getSeconds();
    month = month < 10 ? '0' + month : month;
    day = day < 10 ? '0' + day : day;
    hour = hour < 10 ? '0' + hour : hour;
    minute = minute < 10 ? '0' + minute : minute;
    second = second < 10 ? '0' + second : second;
    milliSeconds = milliSeconds < 10 ? '00' + milliSeconds : milliSeconds < 100 ? '0' + milliSeconds : milliSeconds;
    var min = 10000,
      max = 99999;
    var random = parseInt(Math.random() * (max - min + 1)) + min;
    var ext = name.substring(name.lastIndexOf('.')),
      folder = 'file';
    if (/(image|audio|video)/.test(type)) {
      folder = type.replace(/^(image|audio|video)(.*)$/, '$1');
    }
    file.folder = folder;
    var key = [path, '/', folder, '/', year, month, day, hour, minute, second, milliSeconds, random, ext].join('');
    return key;
}
function initUploader(bucket,upTokenUrl,path,callback){
    var uploader = new Uploader({
      bos_bucket : bucket,
      uptoken_url : upTokenUrl,
      init: {
        FilesAdded: function (_, files) {
          // console.log('FilesAdded 添加文件', _, files);
        },
        FileUploaded: function (_, file, info) {
          callback && callback(info);
        },
        UploadComplete: function () {
            setTimeout(function(){
                wx.hideLoading({
                  fail:function(e){
                  }
                });
            },200);
        },
        Error:function(){
           callback && callback();
        },
        UploadProgress:function(_,file,progress){
            progress = progress && typeof progress == 'object' ? progress.progress : 0;
            setTimeout(function(){
                      wx.showLoading({
                        title:'已经上传' + progress + '%'
                      });              
              // wx.hideLoading({
              //     complete:function(){
              //         wx.showLoading({
              //           title:'已经上传' + progress + '%'
              //         });
              //     },
              //     fail:function(e){
              //     }
              // });
            },200);
        
        },
        UploadPartProgress:function(_){

        },
        Key: function (_, file, isPostObject) {
          var deferred = Q.defer();
          if(!isPostObject){
            var stm = new StsTokenManager({
              uptoken_url: upTokenUrl
            });
            stm.get(bucket).then(function(payload){
              uploader.setOptions({
                bos_ak: payload.AccessKeyId,
                bos_sk: payload.SecretAccessKey,
                uptoken: payload.SessionToken
              });
              deferred.resolve({
                key: generateKey(path,file)
              });
            }).catch(function(){
                deferred.reject(new Error(''));
            });
          }else{
            deferred.resolve({
              key: generateKey(path,file)
            });
          }
          return deferred.promise;
      }
    }
  });
  return uploader;
};

export default {
  initUploader : initUploader
};


